package com.bw.eureka.jpa.aop;


import com.bw.common.dto.LogDto;
import com.bw.eureka.jpa.annotation.Log;
import com.bw.eureka.jpa.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Slf4j
@Component
public class LogAop {


    @Autowired
    LogService logService;
    @Pointcut(" execution( * com.bw.eureka.jpa.controller.*.*(..))")
    public void myPointcut(){}


    @AfterReturning(pointcut = "myPointcut()")
    public void  after(JoinPoint joinPoint){

        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        Log annotation = method.getAnnotation(Log.class);
        if (annotation == null){
            return;
        }

        LogDto logDto = new LogDto();
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        logDto.setPort(request.getServerPort()+"");
        logDto.setUrl(request.getRequestURL().toString());
        logDto.setRequestType(request.getMethod());
        logDto.setHost(request.getLocalAddr());
        Object[] args = joinPoint.getArgs();
        logDto.setMethodAgs(args);
        String methodName = method.getName();
        logDto.setMethodName(methodName);
        logDto.setDesc(annotation.value());
        logDto.setCreateTime(new Date());
        log.info("自定义注解 拦截 controller 请求......");
        // logService.saveLog(logDto);
    }
}
